import * as vscode from 'vscode';
import { deleteGitBranch, getAllGitBranches, switchGitBranch } from '../../utils/git';


export class GitBranchTreeItem extends vscode.TreeItem {
  constructor(
    public readonly label: string,
    public readonly collapsibleState: vscode.TreeItemCollapsibleState,
    public contextValue?: string, // 定义上下文值
    iconPath?: string | vscode.ThemeIcon, // 图标路径
  ) {
    super(label, collapsibleState);
    this.iconPath = iconPath;
  }
}

export class GitTreeViewProvider implements vscode.TreeDataProvider<GitBranchTreeItem> {
  private _onDidChangeTreeData: vscode.EventEmitter<GitBranchTreeItem | undefined> = new vscode.EventEmitter<GitBranchTreeItem | undefined>();
  readonly onDidChangeTreeData: vscode.Event<GitBranchTreeItem | undefined> = this._onDidChangeTreeData.event;

  /** 是否显示远程分支 */
  public showRemote = false;

  refresh(): void {
    this._onDidChangeTreeData.fire(undefined);
  }

  getTreeItem(element: GitBranchTreeItem): vscode.TreeItem {
    return element;
  }

  getChildren(element?: GitBranchTreeItem): Thenable<GitBranchTreeItem[]> {
    if (!element) {
      // 返回根节点
      return Promise.resolve([
        new GitBranchTreeItem('Git Branch', vscode.TreeItemCollapsibleState.Collapsed, 'branckRefresh', new vscode.ThemeIcon('git-branch')),
      ]);
    }

    if (element.label === 'Git Branch') {
      return this.getGitBranchTreeItem();
    }
    return Promise.resolve([]);
  }

  toggleNodeState(node: GitBranchTreeItem): void {
    node.contextValue = node.contextValue === 'default' ? 'activated' : 'default';
    this.refresh();
  }


  async getGitBranchTreeItem(): Promise<GitBranchTreeItem[]> {
    const workspaceFolders = vscode.workspace.workspaceFolders;

    if (!workspaceFolders || workspaceFolders.length === 0) {
      throw new Error('No workspace folder is opened.');
    }

    const res:string[] = await getAllGitBranches(workspaceFolders[0]?.uri?.fsPath, this.showRemote) as string[];

    return Promise.resolve(res?.filter(branch => branch !== '/')?.map(branch => {
      return new GitBranchTreeItem(
        branch,
        vscode.TreeItemCollapsibleState.None,
        'branckEdit',
        new vscode.ThemeIcon('git-branch')
      );
    }));
  }
}


export function registerView(context: vscode.ExtensionContext) {
  const gittreeViewProvider = new GitTreeViewProvider();

  vscode.window.registerTreeDataProvider('zd.gittree', gittreeViewProvider);

  context.subscriptions.push(
    vscode.commands.registerCommand('zd-vscode-tools.deleteBranch', async (node: GitBranchTreeItem) => {
      const confirmation = await vscode.window.showWarningMessage(
        '确定删除当前分支?',
        { modal: true }, // 设置为模态对话框
        '确定', // 确认按钮
        '取消' // 取消按钮
      );


      if (confirmation === '确定') {
        const workspaceFolders = vscode.workspace.workspaceFolders;

        if (!workspaceFolders || workspaceFolders.length === 0) {
          throw new Error('No workspace folder is opened.');
        }
        await deleteGitBranch(node.label, workspaceFolders?.[0]?.uri.fsPath);
        gittreeViewProvider.refresh();
      }

    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand('zd-vscode-tools.switchBranch', async (node: GitBranchTreeItem) => {

      const workspaceFolders = vscode.workspace.workspaceFolders;

      if (!workspaceFolders || workspaceFolders.length === 0) {
        throw new Error('No workspace folder is opened.');
      }
      await switchGitBranch(node.label, workspaceFolders?.[0]?.uri.fsPath);
      gittreeViewProvider.refresh();
    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand('zd-vscode-tools.refreshBranch', async (node: GitBranchTreeItem) => {
      gittreeViewProvider.refresh();
    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand('zd-vscode-tools.showRemoteBranch', async (node: GitBranchTreeItem) => {
      gittreeViewProvider.showRemote = !gittreeViewProvider.showRemote;
      gittreeViewProvider.refresh();
    })
  );

}


